package com.programmercarl.greed;

/**
 * https://leetcode.cn/problems/maximum-subarray/description/
 * 最大子数组和  动态规划 AC
 *
 * @author yulongtian
 * @create 2025-02-06 16:16
 */
public class Test03 {
    public static void main(String[] args) {
        Test03 test03 = new Test03();
        System.out.println(test03.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
    }

    // dp[i]=max(dp[i-1]+nums[i],nums[i])
    public int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int max = dp[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
            if(dp[i] > max){
                max = dp[i];
            }
        }
        return max;
    }
}
